package com.timmy.video.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.timmy.video.utils.AutoUtils;
import com.timmy.video.R;
import com.timmy.video.adapter.VideoAdapter;
import com.timmy.video.bean.User;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;

import io.realm.Realm;
import io.realm.RealmResults;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "gzw";
    private RecyclerView mRecyclerView;
    private Realm mRealm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AutoUtils.setSize(this, false, 750, 1334);//没有状态栏,设计尺寸的宽高
        setContentView(R.layout.activity_main);
        initView();
        initSdCard();
    }


    public static String SDDRECTORY = Environment.getExternalStorageDirectory().getPath() + File.separator;
    public static String SDCARDPATH = SDDRECTORY + "gzw/";

    /*固件升级文件*/
    public static String UPDATE_FILE = SDCARDPATH + "update/";

    private void initSdCard() {

        File file1 = new File(UPDATE_FILE + "gzw.zip");
        Log.i(TAG, "initSdCard: " + file1);
        file1.mkdirs();
        if (file1.exists()) {
            Log.i(TAG, "存在");
            //file1.delete();
        }else {
            Log.i(TAG, "不存在");
        }
    }

    private void initRealm() {

        // 获取Realm实例
        mRealm = Realm.getDefaultInstance();

        //addData();


        // 添加查询条件
        // query.equalTo("age", 18);

        // 执行查询
        query();

        if (true) {
            // return;
        }

        // 修改
        mRealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                User myPuppy = realm.where(User.class).equalTo("name", "张三").findFirst();
                myPuppy.setAge(18);
            }
        });

        query();

        // 删除
        // 获取查询结果


        // 所有对数据的变更必须在事物中进行
        mRealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                // 移除符合条件的单个查询结果
                // results.deleteFirstFromRealm();
                //User user = realm.where(User.class).equalTo("age", 20).findFirst();
                // results.deleteLastFromRealm();

                // 移除单个对象
//                 User user = results.get(0);
                //user.deleteFromRealm();

                RealmResults<User> users = mRealm.where(User.class)
                        .not()
                        .in("name", new String[]{"李四"})
                        .findAll();


                // 移除所有符合条件的查询结果
                users.deleteAllFromRealm();
            }
        });

        query();

    }

    private void query() {


        Log.i(TAG, "==============================");

        // 执行查询
        RealmResults<User> result2 = mRealm.where(User.class)
                //.greaterThan("age", 10)  // 隐式地AND
                .findAll();

        for (User user1 : result2) {
            Log.i(TAG, "第二个: " + user1.getName() + " " + user1.getAge());
        }

        Log.i(TAG, "==============================");
    }

    private void addData() {

        mRealm.beginTransaction();
        //... 在这里添加或者升级对象 ...
        User user = mRealm.createObject(User.class);

        user.setAge(18);
        user.setName("张三");

        mRealm.commitTransaction();

        if (true) {
            return;
        }

        //=========================

        mRealm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm bgRealm) {
                User user = bgRealm.createObject(User.class);
                user.setAge(18);
                user.setName("李四");
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                // 事物成功完成
                Log.i(TAG, "添加成功");
            }
        });

    }

    private void initView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.recycleview);

        VideoAdapter adapter = new VideoAdapter(this);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        ArrayList<VideoInfo> videoInfo = getVideoInfo(this);
        adapter.addData(videoInfo);

    }

    // 获取sd卡上所有的mp4
    public ArrayList<VideoInfo> getVideoInfo(Context context) {
        String[] thumbColumns = new String[]{
                MediaStore.Video.Thumbnails.DATA,
                MediaStore.Video.Thumbnails.VIDEO_ID
        };

        String[] mediaColumns = new String[]{
                MediaStore.Video.Media.DATA,
                MediaStore.Video.Media._ID,
                MediaStore.Video.Media.TITLE,
                MediaStore.Video.Media.MIME_TYPE
        };

        //首先检索SDcard上所有的video
        Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, mediaColumns, null, null, null);

        ArrayList<VideoInfo> videoList = new ArrayList<VideoInfo>();

        if (cursor.moveToFirst()) {
            do {
                VideoInfo info = new VideoInfo();

                info.filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
                info.mimeType = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE));
                info.title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));

                //获取当前Video对应的Id，然后根据该ID获取其Thumb
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
                String selection = MediaStore.Video.Thumbnails.VIDEO_ID + "=?";
                String[] selectionArgs = new String[]{
                        id + ""
                };
                Cursor thumbCursor = context.getContentResolver().query(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI, thumbColumns, selection, selectionArgs, null);

                if (thumbCursor.moveToFirst()) {
                    info.thumbPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA));
                }

                //然后将其加入到videoList
                videoList.add(info);

            } while (cursor.moveToNext());
        }
        return videoList;
    }

    // 点击了事情
    public void onClickItem(VideoInfo data) {
        // Toast.makeText(this, "" + data.filePath    , Toast.LENGTH_SHORT).show();

        Intent intent = new Intent();
        intent.putExtra("data", data);
        intent.setClass(MainActivity.this, PlayVideoActivity.class);
        startActivity(intent);
    }

    public static class VideoInfo implements Serializable {
        public String filePath;
        public String mimeType;
        public String thumbPath;
        public String title;
    }
}
